﻿using SharpSoft.Data.DAOS;
using System;
using System.Collections.Generic;
using System.Text;

namespace SharpSoft.Web
{
    public class AppUser
    {
        public AppUser()
        {

        }
        public AppUser(int uid, string ticket, int status, int roleflag, string uname, string displayname)
        {
            this.UserId = uid;
            this.Ticket = ticket;
            this.Status = status;
            this.RoleFlag = roleflag;
            this.UserName = uname;
            this.DisplayName = displayname ?? uname;
        }
        /// <summary>
        /// 是否为系统根账号（超级用户）
        /// </summary>
        public bool IsRootUser { get; internal set; } = false;

        public int UserId { get; internal set; }
        public string Ticket { get; internal set; }
        public int Status { get; internal set; }
        public string UserName { get; internal set; }
        public string DisplayName { get; internal set; }
        /// <summary>
        /// 用户角色，角色使用位标志定义 如：1:Admin 2:仓管员  4：采购员 8：销售员
        /// 那么当用户角色为10（bin:1010）时用户包含“销售员”|“仓管员”两种角色
        /// </summary>
        public int RoleFlag { get; internal set; }

        public int[] Roles { get; set; }
        /// <summary>
        /// 获取当前用户是否包含指定的角色
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public bool HasRole(int role)
        {
            return ((this.RoleFlag & role) == role);
        }
        public string Permissions { get; internal set; }
        /// <summary>
        /// 获取此用户是否具有指定的权限
        /// </summary>
        /// <param name="permissionName"></param>
        /// <returns></returns>
        public bool GetPermissionEnabled(string permissionName)
        {
            return AppUser.PermissionMap.GetPermissionEnabled(this.Permissions, permissionName);
        }
        /// <summary>
        /// 设置用户具有的权限
        /// </summary>
        /// <param name="pers"></param>
        public void SetPermission(Dictionary<string, bool> pers)
        {
            var data = PermissionMap.GetPermissionData(pers);

            this.Permissions = AppUser.PermissionMap.PermissionsDataToBase64(data);
        }


        public static PermissionMap _PermissionMap;
        /// <summary>
        /// 权限映射表
        /// </summary>
        public static PermissionMap PermissionMap
        {
            get
            {
                //if (_PermissionMap == null)
                //{
                //    throw new Exception("权限映射表尚未初始化，无法访问。");
                //}
                return _PermissionMap;
            }
            set
            {
                if (_PermissionMap != null)
                {
                    throw new Exception("权限映射表已经设置过，注意不要重复设置权限映射表。");
                }

                _PermissionMap = value;
            }
        }

    }
}
